"use client";
import { getLoginApi, getUserInfoApi } from "@/api/user";
import { useRouter } from "@/i18n";
import { useGlobalStore } from "@/stores";
import { Toast } from "antd-mobile";
import { useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import dynamic from "next/dynamic";
import { FC, useState } from "react";
import "./page.scss";

interface Props {}

const HeaderBack = dynamic(() => import('@/components/HeaderBack'));
const FromCom = dynamic(() => import('./component/FromCom'));
const GoogleCom = dynamic(() => import('./component/GoogleCom'));
const DomainFooter = dynamic(() => import('@/components/DomainFooter'));

const Login: FC<Props> = () => {
    const t = useTranslations("LoginPage");
    const { setToken, setUserInfo } = useGlobalStore();

    const router: any = useRouter();
    let searchParams = useSearchParams();
    let redirect = searchParams.get("redirect") || "";

    const [msgError, setMsgError] = useState("");
    const loginRequest = async ({ userPhone, pwd }: any) => {
        let params = { user_phone: userPhone, pwd };
        let res = await getLoginApi(params);
        if (res.code == 200) {
            setToken(res.data.token);
            Toast.show({
                icon: "loading",
                content: "请求中...",
                duration: 10000,
                maskClickable: false,
            });
            getUserInfoApi().then((res1) => {
                if (res1.code == 200) {
                    Toast.show({ icon: "success", content: t("loginSuc"), maskClickable: false });
                    setUserInfo(res1.data);
                    setTimeout(() => {
                        router.replace("/" + redirect);
                    }, 1000);
                    setMsgError(res.msg || "");
                }
            });
            setMsgError(res.msg || "");
        }
    };

    return (
        <div className="login-box">
            <HeaderBack showBack={false}/>
            <div className="content-box">
                <GoogleCom />
                <FromCom callbackFun={loginRequest} msgError={msgError} />
                <DomainFooter />
            </div>
        </div>
    );
};

export default Login;
